/******************************************************************************
 * @brief  System module management (including system initialization, time slice polling system)
 *
 * Copyright (c) 2017~2020, <                 >
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 *
 ******************************************************************************/
#include "module.h"
//#include "rf_driver_hal_vtimer.h"

//static volatile unsigned int tick;               //System tick timer

#if 0
/*
 * @brief   Increase the number of system ticks (called in timer interrupt, 1ms 1 time)
 */
void systick_increase(unsigned int ms)
{
    tick += ms;
}
#endif

/*
 * @brief       Get the system tick clock value (usually the unit is 2.4414us)
 */
__attribute__((weak)) uint32_t get_tick(void)
{
    return 0;
}

/*
 * @brief  check timeout
 * @param[in]   start   -
 * @param[in]   timeout -
 */
bool is_timeout(uint32_t start, uint32_t timeout)
{
    return get_tick() - start > timeout;
}

/*
 * @brief       Empty processing, used to locate segment entry
 */
static void nop_process(void) {}

//first initializer
const init_item_t init_tbl_start __attribute__((used)) USER_SECTION("init.item.0") =
{
    "", nop_process
};
//last initializer
const init_item_t init_tbl_end __attribute__((used)) USER_SECTION("init.item.4") =
{
    "", nop_process
};

//first task item
const task_item_t task_tbl_start __attribute__((used)) USER_SECTION("task.item.0") =
{
    "", nop_process
};
//last task item
const task_item_t task_tbl_end __attribute__((used)) USER_SECTION("task.item.2") =
{
    "", nop_process
};

/*
 * @brief       Module initial processing
 *              optimization level: system_init > driver_init > module_init
 * @param[in]   none
 * @return      none
 */
void module_task_init(void)
{
    const init_item_t *it = &init_tbl_start;

    while(it < &init_tbl_end)
    {
        it++->init();
    }
}

/*
 * @brief       task polling
 * @param[in]   none
 * @return      none
 */
void module_task_process(void)
{
    const task_item_t *t;

    for(t = &task_tbl_start + 1; t < &task_tbl_end; t++)
    {
        if((get_tick() - *t->timer) >= t->interval)
        {
            *t->timer = get_tick();
            t->handle();
        }
    }
}
